﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Web.Properties;
using System.Data;

namespace TranTekBE.Price
{

    public class ConnectMysql
    {
        
        private MySqlConnection connection;
        

        //Constructor
        public ConnectMysql()
        {
            Initialize();
        }

        //Initialize values
        private void Initialize()
        {
            string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", "103.28.38.63", "store_22_4_14", "3306", "store_22_4_14", "nhathuoconline");
            // Prepare connecting to the database.
            connection = new MySqlConnection(connectionString);

        }

        //open connection to database
        public bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                //When handling errors, you can your application's response based 
                //on the error number.
                //The two most common error numbers when connecting are as follows:
                //0: Cannot connect to server.
                //1045: Invalid user name and/or password.
                return false;
            }
        }

        //Close connection
        public bool CloseConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                return false;
            }
        }

        public DataTable getDataTable(string  query)
        {
            DataTable dataTable = new DataTable();
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.CommandText = query;
            if (OpenConnection())
            {
                MySqlDataReader dr = cmd.ExecuteReader();
                dataTable.Load(dr);
                dr.Close();
            }
            return dataTable;
        }


        public int QueryData(string query)
        {
            int numRowsUpdated = 0;
            int count = 0;
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.CommandText = query;
            if (OpenConnection())
            {
                numRowsUpdated = cmd.ExecuteNonQuery();
                cmd.Dispose(); 
            }
            cmd.Connection.Close();
            if (numRowsUpdated != 0)
            return count = count + 1;
            
            else
                return count = count + 1;

            
        }

        


        
    }


}